import os
import sys
import logging
import traceback
from common import config, exceptions, utils
from PySide6.QtWidgets import QApplication
from PySide6.QtCore import QTranslator, QLibraryInfo
from PySide6.QtGui import QFontDatabase
from client.login import LoginWindow
from client.main_window import MainWindow
from client.widgets.dialogs import MessageOverlay
from db.models import initDB

def excepthook(exc_type, exc_value, exc_traceback):
    """全局异常钩子"""
    active_window = QApplication.activeWindow()
    if exc_type is KeyboardInterrupt:
        return
    elif exc_type is exceptions.WarningException:
        MessageOverlay.warning(active_window, str(exc_value))
    elif exc_type is exceptions.ErrorException:
        MessageOverlay.error(active_window, str(exc_value))
    elif exc_type is exceptions.DBQueryException:
        MessageOverlay.error(active_window, str(exc_value))
    else:
        MessageOverlay.error(active_window, "程序错误, 请重试。如果问题依旧存在, 请联系开发人员。")
    stack = traceback.format_exception(exc_type, exc_value, exc_traceback)
    logging.error(f"{str(exc_value)}\n  {'  '.join(stack)}\n{'-'*100}")
    sys.__excepthook__(exc_type, exc_value, exc_traceback)

sys.excepthook = excepthook

class AppController:
    def __init__(self):
        self.last_loggin_user = None
        self.login_window = None
        self.main_window = None

    def show_login_window(self):
        self.login_window = LoginWindow()
        self.login_window.LoginSuccess.connect(self.show_main_window)
        self.login_window.show()
        if self.last_loggin_user:
            self.login_window.username_input.setText(self.last_loggin_user["username"])

    def show_main_window(self, user):
        self.last_loggin_user = user
        if user['role'] == utils.UserRole.SALER:
            # 销售员专用一个销售面板不需要其它功能
            pass
        else:
            self.main_window = MainWindow()
            self.main_window.LoggoutSuccess.connect(self.show_login_window)
            self.main_window.show()

    def run(self):
        self.show_login_window()

def load_fonts():
    font_path = os.path.join(os.path.dirname(__file__), "resources", "fonts")
    for font_file in os.listdir(font_path):
        font_path = os.path.join(font_path, font_file)
        QFontDatabase.addApplicationFont(font_path)

def load_qss(app):
    qss_file = os.path.join(os.path.dirname(__file__), "resources", "styles.qss")
    with open(qss_file, "r", encoding="utf-8") as f:
        qss = f.read()
    app.setStyleSheet(qss)

def main():
    os.makedirs(os.path.dirname(config.LOG_FILE), exist_ok=True)
    logging.basicConfig(filename=config.LOG_FILE, level=logging.ERROR, encoding="utf-8",
                        format='%(asctime)s - %(levelname)s - %(message)s')
    initDB()
    translator = QTranslator()
    qt_path = QLibraryInfo.path(QLibraryInfo.TranslationsPath)
    translator.load("qtbase_zh_CN", qt_path)
    app = QApplication(sys.argv)
    load_fonts()
    app.installTranslator(translator)
    controller = AppController()
    controller.run()
    #login_window = LoginWindow()
    #login_window.show()
    load_qss(app)
    #main_window = MainWindow()
    #main_window.show()
    sys.exit(app.exec())

if __name__ == "__main__":
    main()